"""New chat session model (independent from legacy chat_history)."""

from __future__ import annotations

from sqlalchemy import Integer, String, DateTime, func, Boolean, JSON, Column
from app.database import Base


class ChatSession(Base):
    __tablename__ = "chat_sessions"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, index=True, nullable=False)
    title = Column(String(128), nullable=True, index=True)
    system_prompt = Column(String(2000), nullable=True)
    model_name = Column(String(128), nullable=True)
    book_id = Column(Integer, nullable=True, index=True)
    message_count = Column(Integer, default=0, nullable=False)
    tokens_in = Column(Integer, default=0, nullable=False)
    tokens_out = Column(Integer, default=0, nullable=False)
    pinned = Column(Boolean, default=False, nullable=False)
    archived = Column(Boolean, default=False, nullable=False)
    status = Column(String(32), default="active", nullable=False)
    summary_short = Column(String(256), nullable=True)
    summary_compressed = Column(String(4000), nullable=True)
    meta = Column(JSON, nullable=True)
    last_message_at = Column(
        DateTime(timezone=True), server_default=func.now(), nullable=False
    )
    created_at = Column(
        DateTime(timezone=True), server_default=func.now(), nullable=False
    )
    updated_at = Column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False,
    )

    def __repr__(self) -> str:  # pragma: no cover
        return f"<ChatSession id={self.id} user_id={self.user_id} title={self.title}>"
